<template>
	<view>
		<view class="goods-list">
			<view v-for="(goods,i) in goodsList" :key="i" @click="goToDetail(goods)">
				<my-goods :goods='goods'></my-goods>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				//控制是否继续自增(节流阀)
				isLoading: false,
				// 发送请求时要携带的参数对象,声明四个必要参数
				queryObj: {
					query: '',
					cid: '',
					pagenum: 1,
					pagesize: 10
				},
				// 商品列表的数据
				goodsList: [],
				// 商品总数量
				total: 0,
				//图片不存在时默认使用的图片	
				defaultPic: 'https://img0.baidu.com/it/u=3444803971,2413689688&fm=253&fmt=auto&app=120&f=JPEG?w=550&h=500',
			};
		},
		// 页面加载时将所携带的参数转存到queryObj里面
		onLoad(options) {
			console.log('options(查询的关键词)', options);
			this.queryObj.query = options.query || ''
			this.queryObj.cid = options.cid || ''
			this.getGoodsList()
		},
		methods: {
			// 请求数据
			async getGoodsList() {
				const {
					data: res
				} = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
				this.isLoading = false
				if (res.meta.status !== 200) return uni.$showMsg()
				this.goodsList = [...this.goodsList, ...res.message.goods]
				this.total = res.message.total
				console.log('商品列表', this.goodsList);
				console.log('商品总数量', this.total);
			},
			// 点击跳转到商品详情
			goToDetail(goods) {
				uni.navigateTo({
					url: '/subpkg/goods_detail/goods_detail?goods_id=' + goods.goods_id
				})
			},
			// 上拉加载数据
			onReachBottom() {
				if (this.isLoading != false) {
					return
				} else {
					this.queryObj.pagenum++
					console.log(this.queryObj.pagenum);
					if (this.total / 10 >= this.queryObj.pagenum) {
						this.getGoodsList()
					} else {
						this.isLoading = true
						uni.$showMsg('没有更多数据了')
						this.queryObj.pagenum = this.queryObj.pagenum
					}
				}
			},
			// 下拉刷新事件
			onPullDownRefresh() {
				// 重置数据
				this.queryObj.pagenum = 1,
					this.total = 0,
					this.isLoading = false,
					this.goodsList = [],
					// 重新发起请求
					this.getGoodsList().then(() => uni.stopPullDownRefresh())
			}
		}
	}
</script>

<style lang="scss">
	.goods-list {
		.goods-item {
			border-bottom: 1px solid grey;
			display: flex;
			justify-content: space-between;

			.goods-item-left {
				height: 100px;
				width: 100px;

				image {
					display: block;
					width: 100px;
					height: 100px;
				}
			}

			.goods-item-right {
				width: calc(100% - 110px);
				padding: 5px 0;
				display: flex;
				flex-direction: column;
				justify-content: space-evenly;

				.goods-info {
					font-size: 12px;
					color: black;
				}

				.goods-price {
					color: brown;
				}
			}
		}
	}
</style>
